import axios from 'axios'
import { getToken } from '@/utils/helpers'
import router from '@/router'
import { SERVER_URL } from '../config'
import store from '@/store'
import { ToastPlugin } from 'vux'
import Vue from 'vue'
Vue.use(ToastPlugin)

const URL = SERVER_URL + '/api'
const http = axios.create({
  baseURL: URL,
  timeout: 15000
})

http.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer ' + getToken()
  return config
}, error => {
  return Promise.reject(error)
})

http.interceptors.response.use((response) => {
  // Do something with response data
  return response
}, (error) => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        error.message = '正在登陆'
        if (router.currentRoute.path !== '/login') {
          store.commit('SET_TOKEN', '')
          router.push('/login')
        }
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = '请求地址出错'
        break
      case 422:
        if (error.response.data.errors) {
          for (var key in error.response.data.errors) {
            error.message = error.response.data.errors.cname[key][0]
            break
          }
        }
        break
      case 500:
        error.message = '服务器异常'
        break
      default:
    }
    console.log(error.messag)
    let msg = error.response.data.message ? error.response.data.message : error.messag
    Vue.$vux.toast.show({
      text: msg
    })
  }
  return Promise.reject(error)
})
export default http
